import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity, Image, FlatList, TextInput, Alert
} from "react-native";
import { GLOBAL } from '../../../config/global';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { RangTime } from '../../../component/common/RangTime.js';
import { ApproveRefuseModal } from '../../order/approve/details/modals/refuse';
import ToastUtil from '../../../utils/toast';
import StorageHelper from '../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../config/storage';
import { NewAccountHome } from '../../../components/common/newAccountHome';

const scale = GLOBAL.SCALE;
const searchIcon = require('../../../imgs/global/whiteSearch.png');
const calendar = require('../../../imgs/calendar.png');
const TAB_LIST = [
	{
		name: '出库审批',
		id: '1', // TODO
	}, {
		name: '入库审批',
		id: '2', // TODO
	}
]

export class StockApproveListPage extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '出入库通知审批',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: {  // 头部整体样式 
				elevation: 0,
				borderBottomWidth: 0,
				backgroundColor: style.color.themeColor
			},
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};

	constructor(props) {
		super(props);
		this.state = {
			status: 'data',
			companyIndex: 0,
			// showTimeModal: false, // 时间选择
			refreshIcon: false, // 下拉刷新图标
			listData: [], // 列表数据
			saleCount: 0,
			purchaseCount: 0,
			refuseModalVisible: false,
			alertShow: false,
			options: [],
			choice: {}
		}
		this.reload = true; // 判断是整个页面刷新还是下拉刷新
		this.totalPage = 1; // 总页数

		this.pageParams = { // TODO
			id: '1',  // 1:供应商---进项   2:客户---销项
			selectedName: '出库审批',
			searchCode: '',
			pageNo: 1,
			pageSize: 10
		}
		this.selectData = {};
	}

	async componentWillMount() {
		// await this.getSorage();
		await this.initPage();
		await this.getRecord();
	}

	//获取业务组织
	// async  getSorage () {
	// 	const userInfoJson = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
	// 	const userInfo = JSON.parse(userInfoJson);
	// 	this.setState({
	// 		options: userInfo.corpInfoTOs || [],
	// 		choice: this.state.choice.corpId ? this.state.choice : userInfo.corpInfoTOs[0]
	// 	})
	// }

	async initPage() {
		this.setState({
			status: this.reload ? 'loading' : 'data',
			refreshIcon: !this.reload && this.pageParams.pageNo == '1'
		})
		let options = await HTTP.POST(API_GENERATE(API.GET_AUDIT_COUNT), { searchCode: this.pageParams.searchCode });
		options = options || [];
		console.log('this.pageParams========>', this.pageParams)
		const curApi = this.pageParams.id == '1' ? API.GET_SALE_AUDITLIST : API.GET_PURCHASE_AUDITLIST;
		let { corpId } = options[this.state.companyIndex] || {};
		this.pageParams.corpId = corpId || '';
		let res = await HTTP.POST(API_GENERATE(curApi), this.pageParams); // TODO


		if (res) {
			this.totalPage = res.totalPage;
			this.setState({
				status: res.rows && res.rows.length > 0 ? 'data' : 'empty',
				listData: this.pageParams.pageNo == '1' ? res.rows : this.state.listData.concat(res.rows),
				refreshIcon: false,
				options,
				choice: options[this.state.companyIndex] || {}
			})
		} else {
			this.setState({
				refreshIcon: false,
				status: 'error'
			})
		}
	}

	// 获取列表数量
	async getRecord() {
		const { options, companyIndex } = this.state;
		const { corpId } = options[companyIndex] || {};
		this.pageParams.corpId = corpId || '';
		const sale_res = await HTTP.POST(API_GENERATE(API.GET_SALE_AUDITLIST), this.pageParams); // TODO
		const purchase_res = await HTTP.POST(API_GENERATE(API.GET_PURCHASE_AUDITLIST), this.pageParams); // TODO
		this.setState({
			saleCount: sale_res.recordCount || 0,
			purchaseCount: purchase_res.recordCount || 0,
		})
	}

	// 刷新页面
	reloadPage() {
		this.pageParams.pageNo = 1;
		this.reload = true;
		this.getRecord();
		this.initPage();
	}

	// 下拉刷新
	refresh() {
		this.pageParams.pageNo = 1;
		this.reload = false;
		this.getRecord();
		this.initPage();
	}

	// 上拉翻页
	loadMore() {
		if (this.totalPage > this.pageParams.pageNo) {
			this.pageParams.pageNo++;
			this.reload = false;
			this.initPage();
		}
	}

	// tab切换
	changeTab = (item) => {
		this.pageParams.id = item.id;
		this.pageParams.selectedName = item.name;
		this.pageParams.searchCode = '';
		this.reloadPage();
	}

	async _audit() {
		const { choice } = this.state;
		const { corpId } = choice || {};
		if (this.requesting) return;
		this.setState({ refuseModalVisible: false, loaded: true });
		this.requesting = true;
		const api = this.pageParams.id == '1' ? API.GET_SALE_AUDIT_NOTICE : API.GET_PURCHASE_AUDIT_NOTICE;
		const responseData = await HTTP.POST(API_GENERATE(api), {
			businessKey: this.businessKey,
			auditResult: this.isAgreed,
			remark: this.remark, // 填写
			corpId
		});
		this.setState({ loaded: false });
		console.log('responseData', responseData)
		if (responseData) {
			ToastUtil.showSuccess((this.isAgreed == '0') ? '驳回成功' : '审批成功').then(() => {
				this.requesting = false;
				this.getRecord();
				this.initPage();
				if (this.isAgreed != '0') {
					this.props.navigation.navigate('PushEail', { noticeId: this.businessKey, inOutFlag: this.pageParams.id, createName: this.selectData.createName || null });
				}
			})
		} else {
			this.requesting = false;
		}
	}

	_pass() {
		this.isAgreed = 1;
		this.remark = '';
		this.setState({
			refuseModalVisible: true
		})
	}

	_refuse() {
		this.isAgreed = 0;
		this.remark = '';
		this.setState({
			refuseModalVisible: true
		})
	}

	// 日期和筛选
	_renderFilterWrap() {
		return (
			<View style={styles.filterWrap}>
				<Image source={searchIcon} style={styles.searchIcon} />
				<TextInput
					ref="enterpriseInput"
					style={styles.searchInput}
					underlineColorAndroid='transparent'
					placeholder={"请输入企业名称/通知单号"}
					placeholderTextColor="rgba(255, 255, 255, .8)"
					maxLength={30}
					returnKeyType={'search'}
					defaultValue={this.pageParams.searchCode}
					onChangeText={(txt) => { this.pageParams.searchCode = txt; }}
					onSubmitEditing={() => { this.initPage(); this.getRecord() }}
				/>
			</View>
		)
	}

	// tab
	_renderTabWrap() {
		const { saleCount, purchaseCount } = this.state;
		return (
			<View style={styles.tabWrap}>
				{
					TAB_LIST.map((item, index) => {
						return (
							<TouchableOpacity activeOpacity={1} onPress={() => { this.changeTab(item) }} key={index} style={[styles.tabItem, this.pageParams.id == item.id ? { backgroundColor: style.color.themeColor } : { backgroundColor: 'transparent' }]}>
								<Text style={[styles.tabText, this.pageParams.id == item.id ? { color: '#fff' } : { color: style.color.themeColor }]}>{item.name}</Text>
								{(item.id == '1' && saleCount) || (item.id != '1' && purchaseCount) ?
									<View style={[styles.numPoint, this.pageParams.id == item.id ? { backgroundColor: '#fff' } : { backgroundColor: 'red' }]}></View> : null
								}
							</TouchableOpacity>
							// <TouchableOpacity activeOpacity={1} onPress={() => { this.changeTab(item) }} key={index} style={[styles.tabItem, this.pageParams.id == item.id ? null : { borderBottomColor: style.color.themeColor }]}>
							// 	<Text style={[styles.tabText, this.pageParams.id == item.id ? { fontWeight: 'bold' } : { opacity: .8 }]}>{item.name} {item.id == '1' ? saleCount : purchaseCount}</Text>
							// </TouchableOpacity>
						)
					})
				}
			</View>
		)
	}

	// 列表
	_renderListItem = (data) => {
		const { supplierName, companyName, createTime, orderId, noticeId, noticeQuantity, expectExeDate, warehouseName,
			salesManName, organName, outStockStartDate, outStockEndDate, bizTeamName, createName } = data.item;
		return (
			<TouchableOpacity activeOpacity={1} onPress={() => {
				this.props.navigation.navigate('StockApproveDetailPage', {
					title: this.pageParams.selectedName,
					id: this.pageParams.id,
					businessKey: noticeId,
					choice: this.state.choice,
					callback: () => this.reloadPage()
				})
			}} style={{ marginBottom: 18 * scale }}>
				<View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between' }}>
					<Text style={styles.titleText}>{(this.pageParams.id == '1' ? companyName : supplierName) || '-'}</Text>
					<Text style={styles.titleText}>{(createTime || '-').substring(0, 16)}</Text>
				</View>
				<View style={{ backgroundColor: '#fff', borderRadius: 4 * scale }}>
					<View style={styles.billNumWrap}>
						<Text style={styles.commonTitle}>{orderId || '-'}  |  {noticeId || '-'} </Text>
						<Text style={{ fontSize: 10 * scale, paddingBottom: 12 * scale, paddingTop: 8 * scale, color: '#848A96' }}>(业务组织：{this.state.choice.corpName || '-'})</Text>
					</View>

					<View style={styles.billInfoWrap}>
						<View style={{ flexDirection: 'row', alignItems: 'center' }}>
							<Text style={styles.commonTitle}>通知量（吨）</Text>
							<Text style={styles.commonTitle}>{this.pageParams.id == '1' ? '发货仓库' : '收货仓库'}</Text>
							<Text style={styles.commonTitle}>{this.pageParams.id == '1' ? '出货日期' : '收货日期'}</Text>
						</View>
						<View style={{ flexDirection: 'row', alignItems: 'flex-start' }}>
							<Text style={styles.commonText}>{(noticeQuantity || 0).toFixed(3)}</Text>
							<Text style={styles.commonText}>{warehouseName || '-'}</Text>
							{
								this.pageParams.id == '1' ?
									<View style={{ flex: 1 }}>
										<Text style={styles.commonText}>
											{outStockStartDate ? outStockStartDate.substring(0, 10) : null}
										</Text>
										<Text style={[styles.commonText, { paddingTop: 2 * scale }]}>
											{outStockEndDate ? outStockEndDate.substring(0, 10) : null}
										</Text>
									</View>
									:
									<Text style={styles.commonText}>{(expectExeDate || '-').substring(0, 10)}</Text>
							}
						</View>
					</View>

					<View style={styles.billInfoWrap}>
						<View style={{ flexDirection: 'row' }}>
							<View style={{ flex: 2 }}>
								<Text style={[styles.commonTitle]}>业务员</Text>
							</View>
							<View style={{ flex: 1 }}>
								<Text style={styles.commonTitle}>制单人</Text>
							</View>
						</View>
						<View style={{ flexDirection: 'row' }}>
							<Text style={[styles.commonText, { flex: 2, paddingRight: 15 * scale }]}>
								{salesManName || '-'} | {bizTeamName || '--'} | {organName || '-'}
							</Text>
							<View style={{ flex: 1 }}>
								<Text style={styles.commonText}>{createName || '-'}</Text>
							</View>
						</View>
					</View>

					<View style={styles.buttonBox}>
						<TouchableOpacity style={styles.buttonPass} activeOpacity={1} onPress={() => {
							this.businessKey = noticeId;
							this.selectData = data.item;
							this._pass();
						}}>
							<Text style={styles.buttonPassText}>通过</Text>
						</TouchableOpacity>
						<TouchableOpacity style={styles.buttonRefuse} activeOpacity={1} onPress={() => {
							this.businessKey = noticeId;
							this._refuse();
						}}>
							<Text style={styles.buttonRefuseText}>驳回</Text>
						</TouchableOpacity>
					</View>
				</View>

			</TouchableOpacity>
		)
	}

	render() {
		let { status, listData, refreshIcon, alertShow, choice, options } = this.state;
		return (
			<View style={styles.container}>
				<View style={styles.headerWrap}>
					{this._renderFilterWrap()}
				</View>
				{options.length > 1 ?
					<NewAccountHome
						fn={(val) => { this.setState({ companyIndex: val }, () => { this.pageParams.pageNo = 1; this.reloadPage(); this.getRecord() }) }}
						options={options}
						choice={choice} />
					: null}
				{this._renderTabWrap()}
				{
					status == 'data' ? (
						<View style={{ flex: 1, paddingTop: 20 * scale, paddingBottom: 10 * scale, paddingLeft: 16 * scale, paddingRight: 16 * scale }}>
							<FlatList
								data={listData}
								renderItem={this._renderListItem}
								refreshing={refreshIcon}
								onRefresh={() => { this.refresh() }}
								onEndReachedThreshold={0.1}
								onEndReached={() => { this.loadMore() }}
							/>
						</View>) : null
				}


				{
					status != 'data' ? (<PageStatusIndex status={status} emptyText={'暂无记录'} onErrorPress={this.reloadPage} />) : null
				}

				<ApproveRefuseModal
					titleText={'审批意见'}
					placeholderText={this.isAgreed ? '请输入同意原因' : null}
					propsDefaultValue={this.isAgreed ? '审批同意' : '审批驳回'}
					visible={this.state.refuseModalVisible}
					btnPress={(remark) => {
						this.remark = remark;
						this._audit();
					}}
					bgPress={() => {
						this.setState({
							refuseModalVisible: false,
						});
					}} />
			</View >
		)
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray,
	},
	headerWrap: {
		backgroundColor: style.color.themeColor,
		paddingLeft: 17 * scale,
		paddingRight: 17 * scale,
		paddingBottom: 20 * scale,
	},
	filterWrap: {
		marginTop: 15 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		position: 'relative',
	},
	dateWrap: {
		width: 110 * scale,
		height: 36 * scale,
		paddingLeft: 36 * scale,
		borderRadius: 18 * scale,
		backgroundColor: 'rgba(255 ,255 , 255, .18)',
		flexDirection: 'row',
		justifyContent: 'center',
		paddingRight: 14 * scale,
	},
	dateImgWrap: {
		width: 36 * scale,
		height: 36 * scale,
		borderRadius: 18 * scale,
		backgroundColor: 'rgba(255, 255, 255, .08)',
		position: 'absolute',
		top: 0,
		left: 0,
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
	},
	dateText: {
		fontSize: 10 * scale,
		color: '#fff',
		opacity: .8,
		textAlign: 'center'
	},
	dateLine: {
		width: 7 * scale,
		height: 1 * scale,
		backgroundColor: 'rgba(255, 255, 255, .36)',
		marginTop: 3 * scale,
		marginBottom: 3 * scale,
	},
	searchInput: {
		height: 36 * scale,
		width: '100%',
		paddingLeft: 42 * scale,
		// paddingRight: 12 * scale,
		backgroundColor: 'rgba(255, 255, 255, .18)',
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		paddingVertical: 0,
		position: 'relative',
		borderRadius: 18 * scale,
		color: '#fff',
		fontSize: 13 * scale
	},
	searchIcon: {
		width: 22 * scale,
		height: 22 * scale,
		position: 'absolute',
		left: 12 * scale,
		top: 8 * scale,
		zIndex: 9,
		opacity: 0.8,
	},
	tabWrap: {
		backgroundColor: style.color.bgGray,
		flexDirection: 'row',
		alignItems: 'center',
		paddingTop: 10,
		paddingBottom: 10
	},
	tabItem: {
		// flex:1,
		paddingTop: 5 * scale,
		paddingBottom: 5 * scale,
		paddingLeft: 16 * scale,
		paddingRight: 16 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		marginHorizontal: 10,
		borderWidth: 1,
		borderRadius: 20,
		borderColor: style.color.themeColor
	},
	tabText: {
		color: '#fff'
	},
	numPoint: { backgroundColor: '#fff', width: 5, height: 5, position: 'absolute', borderRadius: 16, right: 10, top: 5 },
	billNumWrap: {
		borderStyle: 'solid',
		borderBottomColor: '#E3E7F0',
		borderBottomWidth: 1 * scale,
		flexDirection: 'column',
		alignItems: 'flex-start',
		paddingLeft: 14 * scale,
		paddingRight: 14 * scale,
		paddingTop: 16 * scale,
	},
	billInfoWrap: {
		flexDirection: 'column',
		alignItems: 'flex-start',
		justifyContent: 'flex-start',
		paddingLeft: 14 * scale,
		paddingRight: 14 * scale,
		paddingTop: 24 * scale,
	},
	commonTitle: {
		flex: 1,
		color: '#030303',
		fontSize: 12 * scale,
		minWidth: 64 * scale,
	},
	commonText: {
		flex: 1,
		fontSize: 13 * scale,
		color: '#0C0C0D',
		fontWeight: '700',
		paddingTop: 8 * scale,
	},
	buttonPass: {
		width: 68 * scale,
		backgroundColor: style.color.themeColor,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		marginBottom: 12 * scale,
		marginRight: 14 * scale,
		borderRadius: 16 * scale,
		borderColor: style.color.themeColor,
		borderWidth: 1,
	},
	buttonPassText: {
		color: '#fff',
		fontSize: 12 * scale,
		fontWeight: '700',
		textAlign: 'center'
	},
	buttonRefuse: {
		width: 68 * scale,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		marginBottom: 12 * scale,
		borderRadius: 16 * scale,
		borderColor: style.color.themeColor,
		borderWidth: 1,
		marginRight: 14 * scale,
	},
	buttonRefuseText: {
		color: style.color.themeColor,
		fontSize: 12 * scale,
		fontWeight: '700',
		textAlign: 'center'
	},
	titleText: {
		color: '#848A96',
		marginBottom: 6 * scale,
		fontSize: 12 * scale
	},
	buttonBox: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'flex-end',
		marginTop: 18 * scale
	},
	accountSelect: {
		backgroundColor: style.color.themeColor,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center'
	}
})